﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NopSolutions.NopCommerce.BusinessLogic;
using brevis.Nop.Report.Data.OrderTableAdapters;
using System.Configuration;

namespace brevis.Nop.SDK.Checker
{
    public class UserOrderMatch : IChecker
    {
        /// <summary>
        /// Checks if user matches with order by guid
        /// </summary>
        /// <param name="param">NopContext and HttpContext as object-Array</param>
        /// <returns></returns>
        public void Execute(object[] param)
        {
            var nopcontext = (NopContext) param[0];
            var httpcontext = (HttpContext) param[1];

            if (nopcontext.Session == null 
                || nopcontext.Session.CustomerId == 0)
                throw new UnauthorizedAccessException("user has not logged in correctly.");
                        
            var taOrder = new Nop_Report_OrderTableAdapter();
            taOrder.Connection.ConnectionString = 
                ConfigurationManager.ConnectionStrings["NopSqlConnection"].ConnectionString;

            var orderQueryString = httpcontext.Request.QueryString["orderid"];
            if (string.IsNullOrEmpty(orderQueryString))
                throw new NullReferenceException(
                    "parameter [orderid] is missing in querystring. " +
                    "this check depends on this parameter.");
            
            var orderId = Convert.ToInt64(orderQueryString);

            var order = (from o in taOrder.GetData().AsQueryable() 
                         where o.OrderID == orderId
                         select o).FirstOrDefault();

            if (order.CustomerID != nopcontext.Session.CustomerId)
                throw new UnauthorizedAccessException(
                    string.Format("user is not allowed to open order with id [{0}].",order.OrderID)); 


        }

        /// <summary>
        /// Can't check if user matches with order by guid
        /// </summary>
        /// <returns></returns>
        public void Execute()
        {
            throw new Exception(
                "checker needs some parameters to check if order guid matches with user.");
        }
    }
}
